/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Visao.Gerente.Gerenciar;

import Controle.Controlador;
import Modelo.Acompanhamento;
import java.awt.Color;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author Andre Luiz
 */
public class GerenciarAcompanhamentos extends javax.swing.JFrame {
    ArrayList<Acompanhamento> acompanhamentos;
    DefaultTableModel modelo;
    TableRowSorter sorter;
    
    /**
     * Creates new form GerenciarAcompanhamentos
     */
    public GerenciarAcompanhamentos() {
        initComponents();
        modelo = (DefaultTableModel) jtAcompanhamentos.getModel();
        sorter = new TableRowSorter(modelo);
        jScrollPane1. getViewport().setBackground(Color.WHITE);
        jtAcompanhamentos.getColumnModel().getColumn(0).setMinWidth(0);
        jtAcompanhamentos.getColumnModel().getColumn(0).setMaxWidth(0);
        jtAcompanhamentos.getColumnModel().getColumn(1).setPreferredWidth(300);
        jtAcompanhamentos.getColumnModel().getColumn(2).setPreferredWidth(40);
        acompanhamentos=imprimeDadosTabelas(carregarDadosBD());
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jtAcompanhamentos = new javax.swing.JTable();
        jInserirAcomp = new javax.swing.JButton();
        jEditarAcomp = new javax.swing.JButton();
        jRemoverAcomp = new javax.swing.JButton();
        jtfFiltro = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Gerenciar Acompanamentos");

        jtAcompanhamentos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Cod", "Produto", "Valor"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jtAcompanhamentos.setFillsViewportHeight(true);
        jtAcompanhamentos.setMaximumSize(new java.awt.Dimension(1000, 1000));
        jtAcompanhamentos.setMinimumSize(new java.awt.Dimension(600, 0));
        jtAcompanhamentos.setName("");
        jtAcompanhamentos.setOpaque(false);
        jtAcompanhamentos.setPreferredSize(new java.awt.Dimension(600, 0));
        jScrollPane1.setViewportView(jtAcompanhamentos);

        jInserirAcomp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icones/addAcomp.png"))); // NOI18N
        jInserirAcomp.setToolTipText("Inserir Acompanhamento");
        jInserirAcomp.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jInserirAcomp.setMaximumSize(new java.awt.Dimension(68, 66));
        jInserirAcomp.setMinimumSize(new java.awt.Dimension(68, 66));
        jInserirAcomp.setName("");
        jInserirAcomp.setPreferredSize(new java.awt.Dimension(68, 66));
        jInserirAcomp.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jInserirAcompActionPerformed(evt);
            }
        });

        jEditarAcomp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icones/editarAcomp.png"))); // NOI18N
        jEditarAcomp.setToolTipText("Editar Acompanhamento");
        jEditarAcomp.setMaximumSize(new java.awt.Dimension(68, 66));
        jEditarAcomp.setMinimumSize(new java.awt.Dimension(68, 66));
        jEditarAcomp.setPreferredSize(new java.awt.Dimension(68, 66));
        jEditarAcomp.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jEditarAcompActionPerformed(evt);
            }
        });

        jRemoverAcomp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icones/delAcomp.png"))); // NOI18N
        jRemoverAcomp.setToolTipText("Remover Acompanhamento");
        jRemoverAcomp.setMaximumSize(new java.awt.Dimension(68, 66));
        jRemoverAcomp.setMinimumSize(new java.awt.Dimension(68, 66));
        jRemoverAcomp.setName("");
        jRemoverAcomp.setPreferredSize(new java.awt.Dimension(68, 66));
        jRemoverAcomp.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRemoverAcompActionPerformed(evt);
            }
        });

        jtfFiltro.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jtfFiltroKeyReleased(evt);
            }
        });

        jLabel1.setText("Filtro:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jtfFiltro))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 620, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jEditarAcomp, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jRemoverAcomp, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jInserirAcomp, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jtfFiltro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(82, 82, 82)
                        .addComponent(jInserirAcomp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jEditarAcomp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jRemoverAcomp, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 81, Short.MAX_VALUE)))
                .addContainerGap())
        );

        pack();
        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        java.awt.Dimension dialogSize = getSize();
        setLocation((screenSize.width-dialogSize.width)/2,(screenSize.height-dialogSize.height)/2);
    }// </editor-fold>//GEN-END:initComponents

    private void jInserirAcompActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jInserirAcompActionPerformed
        // Ao clicar no botão Inserir Sabor
        new InserirAlterarAcomp(this).setVisible(true);
    }//GEN-LAST:event_jInserirAcompActionPerformed

    private void jEditarAcompActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jEditarAcompActionPerformed
        //Editar Caregoria
        try {
            int linha = jtAcompanhamentos.getSelectedRow();
            if (linha != -1) {
                int codigo = (int) jtAcompanhamentos.getValueAt(linha, 0);
                new InserirAlterarAcomp(this, codigo).setVisible(true);
            } else {
                throw new Exception("Selecione a linha do Acompanhamento desejado");
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
        }
    }//GEN-LAST:event_jEditarAcompActionPerformed

    private void jRemoverAcompActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRemoverAcompActionPerformed
        // Remover Caregoria
        try {
            int linha = jtAcompanhamentos.getSelectedRow();
            if (linha != -1) {
                int codigo = (int) jtAcompanhamentos.getValueAt(linha, 0);
                Controlador.remover_Acompanhamento(codigo);
                atualizaTabela();
            } else {
                throw new Exception("Selecione a linha do Acompanhamento desejado");
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
        }
    }//GEN-LAST:event_jRemoverAcompActionPerformed

    private void jtfFiltroKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfFiltroKeyReleased
        // Filtro:
        sorter.setRowFilter(RowFilter.regexFilter(jtfFiltro.getText().toUpperCase(),1));
        jtAcompanhamentos.setRowSorter(sorter);
    }//GEN-LAST:event_jtfFiltroKeyReleased

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jEditarAcomp;
    private javax.swing.JButton jInserirAcomp;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JButton jRemoverAcomp;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jtAcompanhamentos;
    private javax.swing.JTextField jtfFiltro;
    // End of variables declaration//GEN-END:variables
    
    /**
     * Carrega todos os categorias do banco de dados
     * @return Retorna uma lista de Sabores 
     */
    private ArrayList<Acompanhamento> carregarDadosBD(){
        ArrayList<Acompanhamento> acomp = new ArrayList<>();
        if(Controlador.carregarDadosBD_Acompanhamentos(acomp)){
            return acomp;
        }
        return null;
    }
    
    private ArrayList<Acompanhamento> imprimeDadosTabelas(ArrayList<Acompanhamento> acomp) {
        // Adiciona uma nova linha em branco no modelo  
        int linhaTabela = 0;
        jtAcompanhamentos.setRowSorter(null); // desabilita o filtro
        
        for (int i = 0; i < acomp.size(); i++) {
            try{
                if (jtAcompanhamentos.getRowCount() <= linhaTabela) {
                    modelo.addRow(new String[]{"", ""});
                }
                jtAcompanhamentos.setValueAt(acomp.get(i).getCodigo(), linhaTabela, 0);
                jtAcompanhamentos.setValueAt(acomp.get(i).getNome().toUpperCase(), linhaTabela, 1);
                jtAcompanhamentos.setValueAt(acomp.get(i).getValor(), linhaTabela, 2);
            }catch(Exception ex){
                System.out.println("Erro ao imprimir os dados na tabela\n"+ex.getMessage());
            }

            linhaTabela++;
        }
        removeLinhasInutilizadas(linhaTabela);
        jtfFiltroKeyReleased(null);
        
        return acomp;
    }
    
    public void removeLinhasInutilizadas(int linhaTabela){
        for (int i = linhaTabela; i < jtAcompanhamentos.getRowCount(); i++) {
            modelo.removeRow(i);
        }
    }
    
    public void atualizaTabela(){
        imprimeDadosTabelas(carregarDadosBD());
    }
}
